package cn.mw.cmdb.template.strategy.handler;

import cn.mw.cmdb.exception.ZabbixResultException;
import cn.mw.cmdb.template.constant.MwTemplateConfigurationConstant;
import cn.mw.cmdb.template.entity.DiscoveryRuleDto;
import cn.mw.cmdb.template.entity.convert.MwDiscoverRuleConvertDto;
import cn.mw.cmdb.template.enums.TemplateDetailEnum;
import cn.mw.cmdb.template.param.DiscoveryRuleFilterParam;
import cn.mw.cmdb.template.param.DiscoveryRuleParam;
import cn.mw.cmdb.template.param.MwTemplateConfigurationParam;
import cn.mw.cmdb.template.strategy.TemplateDetailHandler;
import cn.mw.cmdb.template.utils.TemplateSortUtil;
import cn.mw.microMonitorCommon.constants.ZabbixApiConstants;
import cn.mw.microMonitorCommon.constants.ZabbixMethodConstants;
import cn.mw.microMonitorCommon.entity.zabbix.MWZabbixAPIResult;
import cn.mw.microMonitorCommon.util.ListMapObjUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description 发现规则处理
 */
@Service
@Slf4j
public class DiscoveryRuleHandler extends TemplateDetailHandler {

    private final String filter = "filter";
    private final String CONDITIONS = "conditions";

    @Override
    public TemplateDetailEnum handlerType() {
        return TemplateDetailEnum.DISCOVERIES;
    }

    @Override
    public Object getData(MwTemplateConfigurationParam param) {
        List<DiscoveryRuleDto> discoveryRuleDtos = new ArrayList<>();
        //根据模板ID查询自动发现信息
        Map zabbixRuleParam = new HashMap();
        if(StringUtils.isNotEmpty(param.getTemplateId())){
            zabbixRuleParam.put(MwTemplateConfigurationConstant.TEMPLATE_IDS,param.getTemplateId());
        }
        if(StringUtils.isNotEmpty(param.getHostId())){
            zabbixRuleParam.put(HOST_IDS,param.getHostId());
        }
        zabbixRuleParam.put(MwTemplateConfigurationConstant.OUTPUT, Arrays.asList(MwTemplateConfigurationConstant.ITEM_ID,MwTemplateConfigurationConstant.NAME,key_,delay,type,status,description));
        zabbixRuleParam.put(MwTemplateConfigurationConstant.selectItems, Arrays.asList(MwTemplateConfigurationConstant.NAME,key_,delay,history,trends,type,status,discover));
        zabbixRuleParam.put(MwTemplateConfigurationConstant.selectTriggers, Arrays.asList(MwTemplateConfigurationConstant.DESCRIPTION,priority,OP_DATA,expression,status,discover));
        zabbixRuleParam.put(MwTemplateConfigurationConstant.selectGraphs, Arrays.asList(MwTemplateConfigurationConstant.NAME,width,height,GRAPH_TYPE,discover,description));
        MWZabbixAPIResult ruleResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.DISCOVERY_RULE_GET, zabbixRuleParam);
        if(ruleResult == null || ruleResult.isFail()){
            throw new ZabbixResultException(String.valueOf(ruleResult.getData()));
        }
        List<MwDiscoverRuleConvertDto> ruleConvertDtos = JSONArray.parseArray(String.valueOf(ruleResult.getData()), MwDiscoverRuleConvertDto.class);
        if(CollectionUtils.isEmpty(ruleConvertDtos)){
            return null;
        }
        for (MwDiscoverRuleConvertDto ruleConvertDto : ruleConvertDtos) {
            DiscoveryRuleDto discoveryRuleDto = new DiscoveryRuleDto();
            discoveryRuleDto.extractFrom(ruleConvertDto);
            discoveryRuleDtos.add(discoveryRuleDto);
        }
        if(CollectionUtils.isNotEmpty(discoveryRuleDtos) && StringUtils.isNotEmpty(param.getDetailName())){
            discoveryRuleDtos = discoveryRuleDtos.stream().filter(item->item.getName().contains(param.getDetailName())).collect(Collectors.toList());
        }
        //数据排序
        List realData = TemplateSortUtil.templateSortList(discoveryRuleDtos,param,param.getQuery());
        if(param.getPageNum() == null || param.getPageSize() == null){
            return realData;
        }
        Page page = pageHandler(realData, param.getPageNum(), param.getPageSize());
        return page;
    }

    @Override
    public Object createData(MwTemplateConfigurationParam param) {
        Object detailData = param.getDetailData();
        DiscoveryRuleParam discoveryRuleParam = JSONObject.parseObject(JSONObject.toJSONString(detailData), DiscoveryRuleParam.class);
        Map zabbixParam = ListMapObjUtils.beanToMap(discoveryRuleParam);
        delMapNullValue(zabbixParam);
        hanlderFilter(zabbixParam);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.DISCOVERY_RULE_CREATE, zabbixParam);
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        return null;
    }

    private void hanlderFilter(Map zabbixParam){
        if(zabbixParam.containsKey(filter)){
            DiscoveryRuleFilterParam filterParam = (DiscoveryRuleFilterParam) zabbixParam.get(filter);
            Map map = ListMapObjUtils.beanToMap(filterParam);
            List<DiscoveryRuleFilterParam.FilterCondition> conditions = filterParam.getConditions();
            List<Map> listMaps = new ArrayList<>();
            for (DiscoveryRuleFilterParam.FilterCondition condition : conditions) {
                Map beanToMap = ListMapObjUtils.beanToMap(condition);
                delMapNullValue(beanToMap);
                listMaps.add(beanToMap);
            }
            map.put(CONDITIONS,listMaps);
            delMapNullValue(map);
            zabbixParam.put(filter,map);
        }
    }

    @Override
    public Object updateData(MwTemplateConfigurationParam param) {
        Object detailData = param.getDetailData();
        DiscoveryRuleParam discoveryRuleParam = JSONObject.parseObject(JSONObject.toJSONString(detailData), DiscoveryRuleParam.class);
        Map zabbixParam = ListMapObjUtils.beanToMap(discoveryRuleParam);
        delMapNullValue(zabbixParam);
        hanlderFilter(zabbixParam);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.DISCOVERY_RULE_UPDATE, zabbixParam);
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        return null;
    }

    @Override
    public Object deleteData(MwTemplateConfigurationParam param) {
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.DISCOVERY_RULE_DELETE, param.getDetailDeleteIds());
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        return null;
    }

    @Override
    public Object selectDataById(MwTemplateConfigurationParam param) {
        Map zabbixParam = new HashMap();
        zabbixParam.put(MwTemplateConfigurationConstant.ITEM_IDS,Arrays.asList(param.getDetailId()));
        zabbixParam.put(MwTemplateConfigurationConstant.OUTPUT,MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectFilter,MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectLLDMacroPaths,MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectPreprocessing,MwTemplateConfigurationConstant.EXTEND);
        zabbixParam.put(MwTemplateConfigurationConstant.selectOverrides,MwTemplateConfigurationConstant.EXTEND);
        MWZabbixAPIResult zabbixAPIResult = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.DISCOVERY_RULE_GET, zabbixParam);
        if(zabbixAPIResult == null || zabbixAPIResult.isFail()){
            throw new ZabbixResultException(String.valueOf(zabbixAPIResult.getData()));
        }
        List<DiscoveryRuleParam> discoveryRuleParams = JSONArray.parseArray(String.valueOf(zabbixAPIResult.getData()), DiscoveryRuleParam.class);
        if(CollectionUtils.isEmpty(discoveryRuleParams)){return null;}
        return discoveryRuleParams.get(0);
    }
}
